#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年2月22日

@author: Administrator
'''
from PIL import Image
from attachment import settings
from attachment.models import Attachment
from attachment.tasks import update_oss_file_to_es_task
from common.utils import tool, storage
from django.http.response import HttpResponse
import StringIO
import copy

def upload_image(file_content, suffix="jpg", optimize=None, app_label=settings.ATTACHMENT_MEDIA_PATH, fpath=None,):
    u'''
    function: 图片附件上传
    
    upfile - 上传的文件
    suffix   - 后缀
    app_label - app 名称
    fpath  - 文件路径
    optimize - 0/1 图片是否优化处理(非必须)
    
    return: record = {'id': xxx, 'name': zzz, 'fpath': 'xxxx', 'url': yyy, 'width': xxx, 'height': xxxx}
    '''
        
    if fpath:
        storage.save_path(file_content, fpath, optimize)
    else:
        fpath = storage.save(file_content, dir_path=app_label, suffix=suffix, optimize=optimize)
    im = Image.open(StringIO.StringIO(file_content))
    width, height = im.size
    del im
    return fpath, width, height

def upload_file(file_content, suffix="txt", app_label=settings.ATTACHMENT_MEDIA_PATH, fpath=None):
    u'''
    function: 图片附件上传
    
    file_content - 上传的文件内容
    suffix   - 后缀
    app_label - app 名称
    fpath  - 文件路径
    optimize - 0/1 图片是否优化处理(非必须)
    
    return: record = {'id': xxx, 'name': zzz, 'fpath': 'xxxx', 'url': yyy}
    '''
    if fpath:
        storage.save_path(file_content, fpath)
    else:
        fpath = storage.save(file_content, dir_path=app_label, suffix=suffix)
        
    return fpath

def update_oss_file_to_es(actions):
    
    if isinstance(actions, str):
        actions = [actions]
    for action in actions:
        _source = {
            "fpath":action,
            "id":action[:action.rfind(".")].replace("/", "_"),
        }
        update_oss_file_to_es_task.delay(_source)
    
